package shiyaokeji_erp

import constant.SystemConstant

class IndexController {
    def afterInterceptor = {
        session.setAttribute(SystemConstant.UserNowInHeadMenuKEY, '首页')
        session.setAttribute(SystemConstant.UserNowInChildMenuKEY, '')
    }
    def index() {
        Menu m = Menu.findByRank(1,[max:1,sort:'id',order:'asc'])
        session.setAttribute(SystemConstant.UserNowInHeadMenuKEY,m.getName())
        session.setAttribute(SystemConstant.UserNowInHeadMenuIcoKEY,m.getIco())
        session.setAttribute(SystemConstant.UserNowInChildMenuKEY,'')

        User user = session.getAttribute(SystemConstant.USER_Session_KEY)
        user=User.findById(user.id)
        Calendar cal = Calendar.getInstance(Locale.CHINA)
        //获取本月进项额
        def ins = Invoice.executeQuery('select tax from Invoice where buyCompany=? and month(dateCreated)=?',[user.company,cal.get(Calendar.MONTH)+1])
        Float inMoney = 0;
        ins.each {
            inMoney+=it
        }
        //获取本月销项额
        def outs = Invoice.executeQuery('select tax from Invoice where sellCompany=? and month(dateCreated)=?',[user.company,cal.get(Calendar.MONTH)+1])
        Float outMoney = 0;
        outs.each {
            outMoney+=it
        }
        //获取总进销余额
        ins = Invoice.executeQuery('select tax from Invoice where buyCompany=?',user.company)
        Float allIn = 0;
        ins.each {
            allIn+=it
        }
        outs = Invoice.executeQuery('select tax from Invoice where sellCompany=?',user.company)
        Float allOut = 0;
        outs.each {
            allOut+=it
        }
        //获取商品及库存信息
        HashMap<Product,Integer> kucun = new HashMap<Product,Integer>()
        def products = Product.list()
        products.each {product->
            Integer aIn=0,aOut=0
            Invoice.executeQuery('select i.count from Invoice as i where i.buyCompany=? and i.product=?',[user.company,product]).each{
                aIn+=it
            }
            Invoice.executeQuery('select i.count from Invoice as i where i.sellCompany=? and i.product=?',[user.company,product]).each{
                aOut+=it
            }
            kucun.put(product,aIn-aOut)
        }
        //最近10条发票
        def invoiceInstanceList = Invoice.list([max:10])
        render view: '/index',model: [productKucun:kucun,inMoney:inMoney,outMoney:outMoney,allMoney:allIn-allOut,invoiceInstanceList:invoiceInstanceList]
    }
}
